package com.xdemo.manager;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.xdemo.model.BaseEntity;

public class DBManager implements IManager {
	
	private SessionFactory sessionFactory;
	
	public DBManager(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void save(BaseEntity entity){
		Session _session = sessionFactory.openSession();
		Transaction _tx = _session.beginTransaction();
		_session.save(entity);
		_tx.commit();
		_session.close();
	}
	
	public void delete(BaseEntity entity) {
		Session _session = sessionFactory.openSession();
		Transaction _tx = _session.beginTransaction();
		_session.delete(entity);
		_tx.commit();
		_session.close();
	}
	
	public void update(BaseEntity entity) {
		Session _session = sessionFactory.openSession();
		Transaction _tx = _session.beginTransaction();
		_session.update(entity);
		_tx.commit();
		_session.close();
	}
	
	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> T get(Class<T> entityType,Serializable key) {
		Session _session = sessionFactory.openSession();
		return (T)_session.get(entityType, key);
	}
	
	public List<?> findByNameQuery(String queryName,String[] keys,Object[] values) {
		Session _session = sessionFactory.openSession();
		Query _query = _session.getNamedQuery(queryName);
		if(keys != null) {
			for(int i=0;i<keys.length;i++) {
				_query.setParameter(keys[i], values[i]);
			}
		}
		List<?> _result = _query.list();
		_session.close();
		return _result;
	}
			
	@Override
	public void start() {
		
	}

	@Override
	public void stop() {
		if(sessionFactory != null) {
			sessionFactory.close();
		}
	}
	
}
